<template>
  <div class="app-container">


    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane :label="ut.title" :name="ut.key" :key="ut.key" v-for="ut in UserTypeList">
        <div>
          <el-input v-model="userViewModel.UserName" size="small" placeholder="姓名" style="width: 200px;"
            class="filter-item" @keyup.enter.native="queryUser" />
          <el-input v-model="userViewModel.LoginName" size="small" placeholder="登录名" style="width: 200px;"
            class="filter-item" @keyup.enter.native="queryUser" />
          <el-input v-model="userViewModel.MobilePhone" size="small" placeholder="手机号" style="width: 200px;"
            class="filter-item" @keyup.enter.native="queryUser" />
          <el-button type="primary" @click="queryUser" size="small" icon="el-icon-search">查询</el-button>
          <el-button type="primary" @click="handleAdd" size="small" icon="el-icon-plus">新增</el-button>
          <el-button type="primary" @click="refreshUser" size="small" icon="el-icon-refresh">刷新</el-button>
          <el-button v-waves style="margin-left: 10px;" size="small" class="filter-item" type="primary"
            icon="el-icon-upload" @click="handlesgmwUpload">导入用户信息</el-button>
        </div>
        <el-table v-loading="loading" :header-cell-style="{background:'#eef1f6',color:'#606266'}" :data="SGMWuserList"
          style="width: 100%;margin-top:30px;" border @sort-change="sortChange">
          <el-table-column label="姓名">
            <template slot-scope="scope">{{ scope.row.UserName }}</template>
          </el-table-column>
          <el-table-column label="登录名">
            <template slot-scope="scope">{{ scope.row.LoginName }}</template>
          </el-table-column>
          <el-table-column label="手机号">
            <template slot-scope="scope">{{ scope.row.MobilePhone }}</template>
          </el-table-column>
          <el-table-column label="职位">
            <template slot-scope="scope">{{ scope.row.Position }}</template>
          </el-table-column>
          <el-table-column label="生日">
            <template slot-scope="scope">{{ scope.row.BirthdayStr}}</template>
          </el-table-column>
          <el-table-column label="创建时间" sortable="custom" prop="CreateTime">
            <template slot-scope="scope">{{ scope.row.CreateTime}}</template>
          </el-table-column>
          <el-table-column align="center" width="240" label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="handleRole(scope)" icon="el-icon-check">分配角色</el-button>
              <!-- <el-button type="text" size="mini" @click="handleMenu(scope)" icon="el-icon-check">权限</el-button> -->
              <el-button type="text" size="mini" @click="handleEdit(scope)" icon="el-icon-edit">编辑</el-button>
              <el-button type="text" size="mini" @click="handleDelete(scope)" icon="el-icon-delete">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件：https://element.eleme.cn/#/zh-CN/component/pagination -->
        <div class="block" style="float:right;margin-top:15px;" v-if="userViewModel.total>0">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="userViewModel.page" :page-sizes="[10, 20, 30, 40,100]" :page-size="userViewModel.pageSize"
            @prev-click="lastPage" @next-click="nextPage" background layout="total, sizes, prev, pager, next, jumper"
            :total="userViewModel.total"></el-pagination>
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-dialog :visible.sync="dialogPerVisible" :title="'查看权限'" :close-on-click-modal="false">
      <el-form :model="user" :rules="rules" ref="user" label-width="100px" label-position="right">
        <el-form-item label="姓名" prop="UserName">
          <el-input v-model="user.UserName" placeholder="姓名" :disabled="true" />
        </el-form-item>
        <el-form-item label="菜单">
          <el-tree ref="tree" :data="roleRoutes" :props="defaultProps" default-expand-all node-key="id"
            class="permission-tree" />
        </el-form-item>
        <div style="text-align:right">
          <el-button type="danger" @click="dialogPerVisible=false">取消</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

<script>

  import { getUserList, addUser, updateUser, deleteUser, uploadImg, isExistUser, handleMenu, handleRole, getISVUserList } from '@/api/user'
  import { deepClone } from "@/utils";
  import { getAllRoleList, getDialogRoleList } from "@/api/role";
  import { getRoutes, getUserMenus } from "@/api/menu";
  import { GetAllOrgList } from "@/api/org";
  import InfoUpload from "./infoUpload";
  import waves from "@/directive/waves"; // Waves directive
  import { GetDictionaryByPCode } from '@/api/dictionary'
  import { reqGetAreaCitys } from "@/api/areacity";

  const defaultUser = {
    UserId: '',
    AccountStatus: '',
    Birthday: '',
    CreateTime: '',
    Company: '',
    Creater: '',
    Department: '',
    Email: '',
    HeadPhoto: '',
    ShowHeadPhoto: '',
    LoginName: '',
    ModifyTime: '',
    Modify: '',
    MobilePhone: '',
    Position: '',
    Remark: '',
    UserName: '',
    UserType: '',
    OrgName: '',
    OrgCode: '',
    OfficeTel: '',
    RegisterDevice: '',
    Sex: '保密',
    Password: '',
    ConfirmPassword: '',
    RoleIdList: [],
    MenuIdList: [],
    HalfMenuIdList: []
  }
  export default {
    components: { InfoUpload },
    directives: { waves },
    data() {
      var validatePass = (rule, value, callback) => {
        var myreg = /(?=^.{7,18}$)(?=(?:.*?\d))(?=.*[a-z])(?=(?:.*?[A-Z]))(?=(?:.*?[!@#$%*()_+^&}{:;?.]){1})(?!.*\s)[0-9a-zA-Z!@#$%*()_+^&.,]*$/;
        if (value === '') {
          callback(new Error('请输入密码'));
        } else if (!myreg.test(value)) {
          callback(new Error('输入密码格式不正确,请包涵大小字母、数字以及!@.符号'));
        } else {
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        var myreg = /(?=^.{7,18}$)(?=(?:.*?\d))(?=.*[a-z])(?=(?:.*?[A-Z]))(?=(?:.*?[!@#$%*()_+^&}{:;?.]){1})(?!.*\s)[0-9a-zA-Z!@#$%*()_+^&.,]*$/;
        if (value === '') {
          callback(new Error('请确认密码'));
        } else if (!myreg.test(value)) {
          callback(new Error('输入密码格式不正确,请包涵大小字母、数字以及!@.符号'));
        } else if (value !== this.user.Password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      var checkPhone = (rule, value, callback) => {
        var myreg = /^[1][0-9]{10}$/;
        if (value === '') {
          callback(new Error('请输入手机号'));
        } else if (!myreg.test(value)) {
          callback(new Error('手机号格式不正确'));
        } else {
          callback();
        }
      };
      var checkEmail = (rule, value, callback) => {
        var myreg = /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/;
        if (value === null || value === '') {
          callback();
        } else if (!myreg.test(value)) {
          callback(new Error('邮箱格式不正确'));
        } else {
          callback();
        }
      };
      var checkLoginName = (rule, value, callback) => {
        var id = this.user.UserId
        if (value === '') {
          callback(new Error('请输入用户名'));
        } else {
          this.isExistUser(id, value).then((res) => {
            if (res)
              callback(new Error('用户名已经存在，请重新输入'));
            else
              callback();
          });
        }
      };

      return {
        userViewModel: {
          page: 1,
          pageSize: 10,
          total: 0,
          UserName: '',
          LoginName: '',
          MobilePhone: '',
          Unumber: '',
          SGMWRecordJob: '',
          AreaCode: '',
          ProvinceCode: '',
          CityCode: '',
          UserType: 'USER',
          OrderBy: 'CreateTime',//排序字段
          SortDir: '' //是否升序
        },
        query: {
          Page: 1,
          PageSize: 10000,
          Total: 0,
          OrderBy: "AreaCode",
          IsAsc: true,
          TypeLevel: -1,
          AreaCode: -1,
          AreaName: "",
          ProvinceCode: -1,
          ProvinceName: "",
          CityCode: -1,
          CityName: ""
        },
        temp: {
          ID: null,
          AreaCode: 101,
          ProvinceCode: 10001,
          CityCode: 10000001,
          DealerCode: "",
          BusinessType: "",
          DealerName: "",
          BusinessNature: "",
          ManagementCode: "",
          ManagementName: "",
          InvestCode: "",
          InvestName: ""
        },
        views: [],
        dialogPerVisible: false,
        dialogVisible: false,
        dialogRoleVisible: false,
        dialogType: '',
        tabs: [],
        activeName: 'USER',
        user: Object.assign({}, defaultUser),
        userTree: Object.assign({}, defaultUser),
        userRole: Object.assign({}, defaultUser),
        SGMWuserList: [],
        JXSuserList: [],
        ISVuserList: [],
        JKuserList: [],
        routes: [],
        roleRoutes: [],
        roles: [],
        areaCitys: [],
        areaDatas: [],
        provinceDatas: [],
        cityDatas: [],
        areaTempDatas: [],
        provinceTempDatas: [],
        cityTempDatas: [],
        tempMark: false,
        allOrg: [],//全部组织列表
        roleList: [],
        typeOptions: [],
        sexList: ['保密', '男', '女'],
        apiPre: process.env.VUE_APP_BASE_API,
        actionUrl: '',
        loading: true,
        dialogTreeVisible: false,
        dialogJXSVisible: false,
        upDialogFormVisible: false,
        defaultRoleProps: {
          children: "children",
          label: "RoleName"
        },
        defaultProps: {
          children: "children",
          label: "title"
        },
        rules: {
          UserName: [
            { required: true, message: "请输入姓名", trigger: "blur" },
            {
              min: 1,
              max: 50,
              message: "长度在 1 到 50 个字符",
              trigger: "blur"
            }
          ],
          LoginName: [
            { required: true, message: "请输入登录名", trigger: "blur" }
            // { validator: checkLoginName, trigger: 'blur' }
          ],
          Password: [
            { required: true, message: "请输入密码", trigger: "blur" },
            { validator: validatePass, trigger: 'blur' }
          ],
          ConfirmPassword: [
            { required: true, message: "请确认密码", trigger: "blur" },
            { validator: validatePass2, trigger: 'blur' }
          ],
          MobilePhone: [
            { required: true, message: "请输入手机号", trigger: "blur" },
            { validator: checkPhone, trigger: 'blur' }
          ],
          Email: [
            { validator: checkEmail, trigger: 'blur' }
          ],
          Birthday: [{ required: true, message: "请选择日期", trigger: "change" }]
        },
        UserTypeList: [
          { key: 'USER', title: '用户' },
          { key: 'TEACHER', title: '讲师' },
          { key: 'STUDENT', title: '学生' }
        ]
      }
    },
    computed: { // 计算属性，只要相关联的值没有改变，直接返回，不再进行计算，与方法区别，缓存
      routesData() {
        return this.routes;
      }
    },
    created() {  // 实例创建完成后执行的代码
      this.queryUser()
      this.searchInit()
      this.actionUrl = this.apiPre + '/Upload/UploadFiles'
    },
    methods: {
      // 区、省、市数据初始化
      async searchInit() {
        let res = await reqGetAreaCitys(this.query);
        if (res.code === 200) {
          this.areaCitys = res.data.Items;
          this.areaDatas = this.areaCitys.filter(s => s.TypeLevel === 1);
          this.provinceDatas = this.areaCitys.filter(s => s.TypeLevel === 2);
          this.cityDatas = this.areaCitys.filter(s => s.TypeLevel === 3);

          this.areaTempDatas = this.areaCitys.filter(s => s.TypeLevel === 1);
          if (!this.isEidt) this.temp.AreaCode = this.areaTempDatas[0].AreaCode;
        }
      },
      // 区域下拉搜索
      AreaSearch() {
        if (this.userViewModel.AreaCode) {
          this.provinceDatas = this.areaCitys.filter(
            s => s.TypeLevel === 2 && s.AreaCode === this.userViewModel.AreaCode
          );
          this.cityDatas = this.areaCitys.filter(
            s => s.TypeLevel === 3 && s.AreaCode === this.userViewModel.AreaCode
          );
        } else {
          this.provinceDatas = this.areaCitys.filter(s => s.TypeLevel === 2);
          this.cityDatas = this.areaCitys.filter(s => s.TypeLevel === 3);
        }
        this.userViewModel.ProvinceCode = null;
        this.userViewModel.CityCode = null;
        this.queryUser();
      },
      // 省份下拉搜索
      ProvinceSearch() {
        if (this.userViewModel.ProvinceCode) {
          this.cityDatas = this.areaCitys.filter(
            s =>
              s.TypeLevel === 3 && s.ProvinceCode === this.userViewModel.ProvinceCode
          );
        } else {
          if (this.userViewModel.AreaCode)
            this.cityDatas = this.areaCitys.filter(
              s => s.TypeLevel === 3 && s.AreaCode === this.userViewModel.AreaCode
            );
          else this.cityDatas = this.areaCitys.filter(s => s.TypeLevel === 3);
        }
        this.userViewModel.CityCode = null;
        this.queryUser();
      },
      // 城市下拉搜索
      CitySearch() {
        this.queryUser();
      },
      handleViewPer(scope) {
        this.dialogPerVisible = true
        this.getUserMenus(scope.row.UserId)
        this.user = deepClone(scope.row);
      },
      async getUserMenus(userId) {
        var res = await getUserMenus(userId)
        this.roleRoutes = res.data
      },
      async getTabList() {
        var res = await GetDictionaryByPCode("UserType")
        if (res && res.data) {
          this.tabs = res.data
        }
      },
      async getAllOrgList() {
        const res = await GetAllOrgList();
        this.typeOptions = res.data.OrgItems;
        this.typeOptions.unshift({ org_code: '', org_name: '全部' })
        this.allOrg = res.data.OrgItems;
      },
      async getRoles() {
        const res = await getDialogRoleList();
        this.roles = res.data.Items;
      },
      async getRoutes() {
        const res = await getRoutes();
        this.serviceRoutes = res.data;
        this.routes = res.data;
      },
      async getUserList(userViewModel) {
        this.loading = true;
        var  res = await getUserList(userViewModel);
        // if (this.userViewModel.UserType == 'USER' || this.userViewModel.UserType == 'TEACHER')
        //   res = await getUserList(userViewModel);
        // else
        //   res = await getISVUserList(userViewModel);
        if (res.data) {
          this.userViewModel.total = res.data.TotalCount;
           this.SGMWuserList = res.data.UserItems;
        }
        // if (this.userViewModel.UserType == 'USER')
        //   this.SGMWuserList = res.data.UserItems;
        // if (this.userViewModel.UserType == 'STUDENT')
        //   this.JXSuserList = res.data.UserItems;
        // if (this.userViewModel.UserType == 'TEACHER')
        //   this.ISVuserList = res.data.UserItems;
        this.loading = false;
      },
      async getAllRoleList() {
        const res = await getAllRoleList();
        if (res.data) {
          this.roleList = res.data;
        }
      },
      async isExistUser(id, loginName) {
        const res = await isExistUser(id, loginName);
        this.tempMark = res.data
        return res.data
      },
      queryUser() {
        this.userViewModel.page = 1;
        this.getUserList(this.userViewModel);
      },
      refreshUser() {
        this.userViewModel.UserName = '';
        this.userViewModel.LoginName = '';
        this.userViewModel.MobilePhone = '';
        this.userViewModel.OrgCode = '';
        this.userViewModel.OrgName = '';

        this.userViewModel.AreaCode = '';
        this.userViewModel.ProvinceCode = '';
        this.userViewModel.CityCode = '';
        this.userViewModel.SGMWRecordJob = '';
        this.userViewModel.Unumber = '';
        this.userViewModel.AgentNumber = '';
        this.userViewModel.page = 1;
        this.getUserList(this.userViewModel);
      },
      sortChange(data) {
        const { prop, order } = data
        console.log(data)
        this.userViewModel.OrderBy = prop
        if (prop == null || prop == "")
          this.userViewModel.OrderBy = "UserID"
        if (order === 'ascending') {
          this.userViewModel.SortDir = 'asc'
        } else {
          this.userViewModel.SortDir = 'desc'
        }
        this.queryUser()
      },
      lastPage(val) {
        this.userViewModel.page = val;
      },
      nextPage(val) {
        this.userViewModel.page = val;
      },
      handleSizeChange(val) {
        this.userViewModel.pageSize = val;
        this.getUserList(this.userViewModel);
      },
      handleCurrentChange(val) {
        this.userViewModel.page = val
        this.getUserList(this.userViewModel)
      },
      handleAdd() {
        this.user = Object.assign({}, defaultUser)
        this.user.UserType = this.userViewModel.UserType
        this.$nextTick(() => {
          this.$refs['user'].clearValidate() //清空上次的错误验证提示
        })
        this.dialogType = 'new';
        this.dialogVisible = true;
      },
      handleEdit(scope) {
        this.dialogType = 'edit';
        this.dialogVisible = true;
        this.user = deepClone(scope.row);
        this.$nextTick(() => {
          this.$refs['user'].clearValidate() //清空上次的错误验证提示
        });
      },
      handleView(scope) {
        this.dialogJXSVisible = true;
        this.user = deepClone(scope.row);
      },
      async confirmUser() {
        //如果把验证失败弹出提示代码放在validate里面则不会弹出错误提示，直接走下面的更新操作代码
        var v;
        this.$refs['user'].validate(valid => {
          v = valid;
        });
        if (!v) {
          return false;
        }
        const isEdit = this.dialogType === 'edit';
        if (isEdit) {
          await updateUser(this.user);
        } else {
          await addUser(this.user)
          this.userViewModel.page = 1
        }
        this.getUserList(this.userViewModel);
        this.dialogVisible = false;
        this.$notify({
          title: "成功",
          type: "success",
          message: "操作成功!"
        });
      },
      handleDelete({ $index, row }) {
        this.$confirm("确认删除?", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(async () => {
            await deleteUser(row.UserId);
            this.$notify({
              title: "成功",
              type: "success",
              message: "操作成功!"
            });
            this.getUserList(this.userViewModel);
          })
          .catch(err => {
            console.error(err);
          });
      },
      handleAvatarSuccess(res, file) {//图片上传成功响应方法
        this.user.HeadPhoto = res.data;
      },
      beforeAvatarUpload(file) {
        const isImg = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 5;

        if (!isImg) {
          this.$notify({
            title: "失败",
            message: "上传头像图片只能是 JPG/JPEG/PNG 格式!",
            type: "error",
            duration: 3000
          });
          return false
        }
        if (!isLt2M) {
          this.$notify({
            title: "失败",
            message: "上传头像图片大小不能超过 5MB!",
            type: "error",
            duration: 3000
          });
          return false
        }
        return true
      },
      handleRole(scope) {
        this.dialogRoleVisible = true
        this.userRole = deepClone(scope.row);
      },
      async confirmRole() {
        const checkedKeys = this.$refs.uRole.getCheckedKeys();
        this.userRole.RoleIdList = checkedKeys;
        await handleRole(this.userRole)
        this.queryUser()
        this.$notify({
          title: "成功",
          type: "success",
          message: "操作成功!"
        });
        this.dialogRoleVisible = false
      },
      handleMenu(scope) {
        this.dialogTreeVisible = true;
        this.userTree = deepClone(scope.row);
        this.$nextTick(() => {
          this.$refs['userTree'].clearValidate() //清空上次的错误验证提示
          this.$refs.tree.setCheckedKeys(this.userTree.MenuIdList);
        });
      },
      async confirmTree() {
        // 获取选中节点id
        const checkedKeys = this.$refs.tree.getCheckedKeys();
        this.userTree.MenuIdList = checkedKeys;

        // 获取半选中节点id
        const halfkeys = this.$refs.tree.getHalfCheckedKeys();
        this.userTree.HalfMenuIdList = halfkeys;

        await handleMenu(this.userTree);
        this.queryUser()
        this.dialogTreeVisible = false;
        this.$notify({
          title: "成功",
          type: "success",
          message: "操作成功!"
        });
      },

      //---------------------数据导入
      handleUpload() {
        this.upDialogFormVisible = true;
      },
      closeupDialog() {
        this.upDialogFormVisible = false;
        this.refreshUser();
      },
      handleClick(tab, event) {
        this.userViewModel.UserType = this.activeName
        this.queryUser()
        // console.log(tab, event);
      }
    }
  }
</script>